package com.dawan.springboot.service;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: dawan
 * @Date: 2017-11-07
 * @Desc: 验证码识别逻辑层
 */
@Service
public class SecurityCodeService {

    /**
     * 下载图片保存路径
     */
    public static String srcPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "/srcPath/";
    /**
     * 素材库
     */
    public static String trainPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "/trainPath/";

    private static Map<BufferedImage, String> trainMap = null;

    /**
     * @Author: chenhan     2017/11/7
     * @Desc: 发送http请求 下载验证码并记录cookie
     * 
     */
    public String[] downloadImage(String url,String imgName) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String res[ ]=new String[3];

        try {
            HttpGet httpGet = new HttpGet(url);
            response = response = httpclient.execute(httpGet);
            if("HTTP/1.1 200 OK".equals(response.getStatusLine().toString())){
                HttpEntity entity = (HttpEntity) response.getEntity();
                Header rescookie=response.getFirstHeader("Set-Cookie");
                if(rescookie!=null){
                    res[0]="true";
                    res[1]=rescookie.getValue().substring(0, 42);
                    InputStream is = entity.getContent();
                    OutputStream os = new FileOutputStream(srcPath+imgName,false);
                    System.out.println("srcPath+imgName = " + srcPath+imgName);
                    int length = -1;
                    byte[] bytes = new byte[1024];
                    while((length = is.read(bytes)) != -1){
                        os.write(bytes, 0, length);
                    }
                    os.close();
                    res[2]=srcPath+imgName;

                }else{
                    res[0]="false";
                }
            }else{
                res[0]="false";
            }
        }
        finally  {
            response.close();
            httpclient.close();
        }
        return res;
    }


    public int isBlue(int colorInt) {
        Color color = new Color(colorInt);
        int rgb = color.getRed() + color.getGreen() + color.getBlue();
        if (rgb == 153) {
            return 1;
        }
        return 0;
    }

    public int isBlack(int colorInt) {
        Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() <= 100) {
            return 1;
        }
        return 0;
    }

    public BufferedImage removeBackgroud(String picFile)
            throws Exception {
        BufferedImage img = ImageIO.read(new File(picFile));
        img = img.getSubimage(5, 1, img.getWidth()-5, img.getHeight()-2);
        img = img.getSubimage(0, 0, 50, img.getHeight());
        int width = img.getWidth();
        int height = img.getHeight();
        for(int x=0; x<width; x++){
            for(int y=0; y<height; y++){
                if(isBlue(img.getRGB(x, y)) == 1){
                    img.setRGB(x, y, Color.BLACK.getRGB());
                }else{
                    img.setRGB(x, y, Color.WHITE.getRGB());
                }
            }
        }
        return img;
    }

    public List<BufferedImage> splitImage(BufferedImage img)
            throws Exception {
        List<BufferedImage> subImgs = new ArrayList<BufferedImage>();
        int width = img.getWidth()/4;
        int height = img.getHeight();
        subImgs.add(img.getSubimage(0, 0, width, height));
        subImgs.add(img.getSubimage(width, 0, width, height));
        subImgs.add(img.getSubimage(width*2, 0, width, height));
        subImgs.add(img.getSubimage(width*3, 0, width, height));
        return subImgs;
    }

    public Map<BufferedImage, String> loadTrainData() throws Exception {
        if (trainMap == null) {
            Map<BufferedImage, String> map = new HashMap<BufferedImage, String>();
            File dir = new File(trainPath);
            File[] files = dir.listFiles();
            for (File file : files) {
                map.put(ImageIO.read(file), file.getName().charAt(0) + "");
            }
            trainMap = map;
        }
        return trainMap;
    }

    public String getSingleCharOcr(BufferedImage img,
                                          Map<BufferedImage, String> map) {
        String result = "#";
        int width = img.getWidth();
        int height = img.getHeight();
        int min = width * height;
        for (BufferedImage bi : map.keySet()) {
            int count = 0;
            if (Math.abs(bi.getWidth()-width) > 2){
                continue;
            }
            int widthmin = width < bi.getWidth() ? width : bi.getWidth();
            int heightmin = height < bi.getHeight() ? height : bi.getHeight();
            Label1: for (int x = 0; x < widthmin; ++x) {
                for (int y = 0; y < heightmin; ++y) {
                    if (isBlack(img.getRGB(x, y)) != isBlack(bi.getRGB(x, y))) {
                        count++;
                        if (count >= min){
                            break Label1;
                        }
                    }
                }
            }
            if (count < min) {
                min = count;
                result = map.get(bi);
            }
        }
        return result;
    }

    /**
     * @Author: chenhan     2017/11/7
     * @Desc: 验证码识别入口
     *
     */
    public String getAllOcr(String file) throws Exception {
        BufferedImage img = removeBackgroud(srcPath + file);
        List<BufferedImage> listImg = splitImage(img);
        Map<BufferedImage, String> map = loadTrainData();
        String result = "";
        for (BufferedImage bi : listImg) {
            result += getSingleCharOcr(bi, map);
        }
        return result;
    }
}
